package com.derbysoft.synxisadapter.dswitch3.service.impl;

import com.derbysoft.dswitch.remote.hotel.dto.HotelAvailRequest;
import com.derbysoft.dswitch.remote.hotel.dto.HotelAvailResponse;
import com.derbysoft.synxisadapter.commons.dto.synxis.OTAHotelAvailRQ;
import com.derbysoft.synxisadapter.commons.dto.synxis.OTAHotelAvailRS;
import com.derbysoft.synxisadapter.dswitch2.translator.Translator;
import com.derbysoft.synxisadapter.dswitch3.service.HotelProviderService;
import com.derbysoft.synxisadapter.webservice.SynXisWebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * User: jason
 * Date: 2012-11-21
 */
@Component("ds3AvailabilityService")
public class AvailabilityServiceImpl extends DS3AbstractService implements HotelProviderService<HotelAvailRequest, HotelAvailResponse> {

    @Autowired
    @Qualifier("ds3AvailRQTranslator")
    private Translator<HotelAvailRequest, OTAHotelAvailRQ, Void> ds3AvailRQTranslator;

    @Autowired
    @Qualifier("getAvailWebService")
    private SynXisWebService<OTAHotelAvailRQ, OTAHotelAvailRS> getAvailWebService;

    @Autowired
    @Qualifier("ds3AvailRSTranslator")
    private Translator<OTAHotelAvailRS, HotelAvailResponse, HotelAvailRequest> ds3AvailRSTranslator;

    @Override
    public HotelAvailResponse execute(HotelAvailRequest request) {
        try {
            OTAHotelAvailRQ otaHotelAvailRQ = ds3AvailRQTranslator.translate(request, null);

            OTAHotelAvailRS otaHotelAvailRS = getAvailWebService.invoke(otaHotelAvailRQ, loadChannel(request.getHeader().getSource()));

            return ds3AvailRSTranslator.translate(otaHotelAvailRS, request);
        } catch (Exception ex) {
            return createErrorResponse(request, ex);
        }
    }

    private HotelAvailResponse createErrorResponse(HotelAvailRequest request, Exception ex) {
        HotelAvailResponse response = new HotelAvailResponse();
        response.setTaskId(request.getHeader().getTaskId());
        response.setError(createDS3ErrorDTO(ex));
        return response;
    }
}
